package com.ilop.sthome.ui.activity.detail.lock;

import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.os.Vibrator;
import android.text.TextUtils;
import android.util.Log;
import android.view.animation.Animation;
import android.view.animation.CycleInterpolator;
import android.view.animation.TranslateAnimation;

import com.example.common.base.BaseBindActivity;
import com.example.common.utils.LiveDataBus;
import com.ilop.sthome.common.CommonId;
import com.ilop.sthome.common.command.SendDeviceCommand;
import com.ilop.sthome.common.command.SiterCommand;
import com.ilop.sthome.data.event.EventAnswerOK;
import com.ilop.sthome.data.greenDao.DeviceInfoBean;
import com.ilop.sthome.utils.greenDao.utils.DeviceDaoUtil;
import com.siterwell.familywellplus.R;
import com.siterwell.familywellplus.databinding.ActivityUnlockBinding;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author skygge
 * @date 2020/4/13.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：开锁界面
 */
public class UnlockActivity extends BaseBindActivity<ActivityUnlockBinding> {

    private String mDeviceName;
    private int mDeviceId;
    private DeviceInfoBean mDevice;
    protected SendDeviceCommand mSendEquipment;

    private boolean flag_is_delete;
    private AtomicBoolean flag_active = new AtomicBoolean(false);

    @Override
    protected int getLayoutId() {
        return R.layout.activity_unlock;
    }

    @Override
    protected void initialize() {
        super.initialize();
        immersionStatusBar(false);
        mDeviceName = getIntent().getStringExtra(CommonId.KEY_DEVICE_NAME);
        mDeviceId = getIntent().getIntExtra(CommonId.KEY_DEVICE_ID,-1);
        mDevice = DeviceDaoUtil.getInstance().findByDeviceId(mDeviceName, mDeviceId);
        DeviceInfoBean deviceInfoBean = DeviceDaoUtil.getInstance().findGatewayByDeviceName(mDeviceName);
        mSendEquipment = new SendDeviceCommand(this, deviceInfoBean);
    }

    @Override
    protected void initView() {
        super.initView();
        if(TextUtils.isEmpty(mDevice.getSubdeviceName())){
            String title = getString(R.string.lock) + mDeviceId;
            mDBind.tvUnlockTitle.setText(title);
        }else{
            mDBind.tvUnlockTitle.setText(mDevice.getSubdeviceName());
        }
    }

    @Override
    protected void initData() {
        super.initData();
        doStatusShow(mDevice.getDevice_status());
        if (!flag_active.get()){
            mDBind.tvUnlockMsg.setText(mContext.getString(R.string.no_actived));
        }
    }

    @Override
    protected void initListener() {
        super.initListener();
        mDBind.unlockNumber.setOnNumberClick(number -> setText(String.valueOf(number)));
        mDBind.tvPwd1.setOnMyTextChangedListener(content -> {
            if (TextUtils.isEmpty(content)) {
                flag_is_delete = false;
                mDBind.tvUnlockCancel.setText(mContext.getString(R.string.cancel));
            } else {
                flag_is_delete = true;
                mDBind.tvUnlockCancel.setText(mContext.getString(R.string.delete));
            }
        });
        mDBind.tvPwd6.setOnMyTextChangedListener(content -> {
            if (!flag_active.get()){
                Vibrator vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
                vibrator.vibrate(800);
                mDBind.llUnlock.startAnimation(shakeAnimation(3));
            }else {
                String inputNumber = mDBind.tvPwd1.getTextContent() + mDBind.tvPwd2.getTextContent() +
                        mDBind.tvPwd3.getTextContent() + mDBind.tvPwd4.getTextContent() +
                        mDBind.tvPwd5.getTextContent() + mDBind.tvPwd6.getTextContent() ;
                mSendEquipment.sendEquipmentCommand(mDevice.getDevice_ID(), inputNumber);
            }
        });
        mDBind.tvUnlockCancel.setOnClickListener(v -> {
            if (flag_is_delete){
                deleteText();
            }else {
                finish();
            }
        });
        mDBind.unlockBack.setOnClickListener(v -> finish());
    }

    @Override
    protected void initDataBus() {
        super.initDataBus();
        LiveDataBus.get().with(CommonId.KEY_ANSWER_OK, EventAnswerOK.class).observe(this, event -> {
            if (event!=null){
                Log.i(TAG, "initDataBus: answerOK");
                if (event.getData_str1().length() == 9) {
                    int cmd = Integer.parseInt(event.getData_str1().substring(0, 4), 16);
                    if (cmd == SiterCommand.EQUIPMENT_CONTROL) {
                        if (CommonId.KEY_SUCCESS.equals(event.getData_str2())) {
                            runOnUiThread(()->{
                                AnimationDrawable mAnimation = (AnimationDrawable) mDBind.ivUnlock.getBackground();
                                mAnimation.start();
                                showToast(getString(R.string.success_test));
                                finish();
                            });
                        }
                    }
                }
            }
        });
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, R.anim.anim_down_out);
    }

    private void doStatusShow(String status) {
        try {
            String draw = status.substring(4,6);
            switch (draw) {
                case "AB":
                case "55":
                case "56":
                    flag_active.set(true);
                    break;
                default:
                    flag_active.set(false);
                    break;
            }
        }catch (Exception e){
            flag_active.set(false);
        }
    }

    /**
     * 设置显示的密码
     *
     * @param text
     */
    private void setText(String text) {
        // 从左往右依次显示
        if (TextUtils.isEmpty(mDBind.tvPwd1.getTextContent())) {
            mDBind.tvPwd1.setTextContent(text);
        } else if (TextUtils.isEmpty(mDBind.tvPwd2.getTextContent())) {
            mDBind.tvPwd2.setTextContent(text);
        } else if (TextUtils.isEmpty(mDBind.tvPwd3.getTextContent())) {
            mDBind.tvPwd3.setTextContent(text);
        } else if (TextUtils.isEmpty(mDBind.tvPwd4.getTextContent())) {
            mDBind.tvPwd4.setTextContent(text);
        }else if (TextUtils.isEmpty(mDBind.tvPwd5.getTextContent())) {
            mDBind.tvPwd5.setTextContent(text);
        } else if (TextUtils.isEmpty(mDBind.tvPwd6.getTextContent())) {
            mDBind.tvPwd6.setTextContent(text);
        }
    }

    /**
     * 删除刚刚输入的内容
     */
    private void deleteText() {
        // 从右往左依次删除
        if (!TextUtils.isEmpty(mDBind.tvPwd6.getTextContent())) {
            mDBind.tvPwd6.setTextContent("");
        } else if (!TextUtils.isEmpty(mDBind.tvPwd5.getTextContent())) {
            mDBind.tvPwd5.setTextContent("");
        } else if (!TextUtils.isEmpty(mDBind.tvPwd4.getTextContent())) {
            mDBind.tvPwd4.setTextContent("");
        } else if (!TextUtils.isEmpty(mDBind.tvPwd3.getTextContent())) {
            mDBind.tvPwd3.setTextContent("");
        }else if (!TextUtils.isEmpty(mDBind.tvPwd2.getTextContent())) {
            mDBind.tvPwd2.setTextContent("");
        } else if (!TextUtils.isEmpty(mDBind.tvPwd1.getTextContent())) {
            flag_is_delete = false;
            mDBind.tvPwd1.setTextContent("");
            mDBind.tvUnlockCancel.setText(mContext.getString(R.string.cancel));
        }
    }

    /**
     * 晃动动画
     * <p>
     * 那么CycleInterpolator是干嘛用的？？
     * Api demo里有它的用法，是个摇头效果！
     * @param counts 1秒钟晃动多少下
     * @return Animation
     */
    public static Animation shakeAnimation(int counts) {
        Animation translateAnimation = new TranslateAnimation(0, 10, 0, 0);
        translateAnimation.setInterpolator(new CycleInterpolator(counts));
        translateAnimation.setRepeatCount(1);//重复次数
        translateAnimation.setDuration(800);
        return translateAnimation;
    }
}
